﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using PddHelper.Api;
using PddHelper.Models;
using SqlSugar;
using System.Net;

namespace WebApiExtend
{
    #region 权限过滤器by后端管理

    /// <summary>
    /// 登录权限过滤器by后端管理
    /// 通过 Authonization Filter 可以实现复杂的权限角色认证、登陆授权等操作
    /// </summary>
    public class AuthorizationFilter : Attribute, IAuthorizationFilter
    {
        /// <summary>
        /// Http上下文 
        /// </summary>
        public HttpContext _httpContext;

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            _httpContext = context.HttpContext;
            var isNoLogin = context.ActionDescriptor.EndpointMetadata.Any(ex => ex.ToString() == typeof(NoLogin).ToString());//绕过登录
            if (!isNoLogin)
            {
                //这里先整个假token使用 数据库手动添加

                var flag = false;
                var token = context.HttpContext.Request.Headers["Token"].ToString();
                var msg = "无权限,需要在Headers中携带Token,获取Token接口:/Login/Login";

                if (string.IsNullOrEmpty(token))
                {
                    msg = "需要在Headers中携带Token,获取Token接口:/Login/Login";
                }
                if (!string.IsNullOrEmpty(token))
                {
                    flag = CheckToken(token);
                }
                if (!flag)//登录异常返回结果
                {
                    var result = new ApiResult<object> { Code = ApiStatusCode.NoPower, Msg = msg };
                    context.Result = new ContentResult
                    {
                        StatusCode = (int)HttpStatusCode.OK,
                        ContentType = "application/json;charset=utf-8",
                        Content = JsonConvert.SerializeObject(result)
                    };
                    return;
                }
            }
        }

        /// <summary>
        /// 检查token是否有效
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userid"></param>
        /// <param name="username"></param>
        public virtual bool CheckToken(string token)
        {
            return false;
        }
    }
    #endregion
}
